<template lang="pug">
data-page(
  v-bind="pageParams"
)
  mt-table(
    v-bind="tableProps"
  )

  edit-form(
    v-bind="editFormProps"
  )
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type EditFormProps,
  type TableProps,
  useNotify,
} from "@scmt/common-components";
import { type QueryPagination, useApi } from "@scmt/core-api";
import {
  type EquipmentEntity,
  type EquipmentQueryParams,
} from "@scmt/api-lis-equipment";
import { useRequest } from "@scmt/common-hooks";

const $api = useApi();
const $notify = useNotify();
const queryPramas = reactive<EquipmentQueryParams>({
  pageNum: 1,
  pageSize: 20,
});
const editingObj = ref<null | EquipmentEntity>(null);
const selectEquipment = defineModel<null | EquipmentEntity>();

const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    const params = Object.assign({}, queryPramas, q);
    return $api.lis.equipment.query(params).then((res) => {
      const { items } = res;

      selectEquipment.value =
        items.find((item) => item.id == selectEquipment.value?.id) || items[0];
      Object.assign(queryPramas, res.pagination);
      return res;
    });
  },
  save: (model: EquipmentEntity) => {
    return $api.lis.equipment.save(model).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  destroy: (ids: string) => {
    return $api.lis.equipment.destroy(ids).then(() => {
      $notify.success("删除成功");

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  listAsOptions: () => {
    return $api.dict.item.listAsOptions("device_category");
  },
});

onMounted(() => {
  request("tableData");
  request("listAsOptions");
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "deviceName",
      label: "设备名称",
    },
  ];

  const headerActions: Action[] = ["add"];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: () => request("tableData"),
    onAct: onPageActions,
    columns: 3,
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        type: "index",
        label: "序号",
        width: "60px",
      },
      {
        prop: "deviceCode",
        label: "设备编码",
      },
      {
        prop: "deviceName",
        label: "设备名称",
      },
      {
        prop: "deviceCategory",
        label: "设备类别",
        render: ({ row }) => {
          const patientType = data.listAsOptions ?? [];
          let resText = row.deviceCategory;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.deviceCategory
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "createTime",
        label: "创建时间",
        format: "datetime",
      },
      {
        label: "操作",
        actions: ["edit", "destroy"],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    currentRow: selectEquipment.value,
    highlightCurrentRow: true,
    onRowClick: (row: any) => {
      selectEquipment.value = row;
    },
  };
  return tableProps;
});

const editFormProps = computed<EditFormProps>(() => {
  const formItems: FormItemProps[] = [
    {
      prop: "deviceName",
      label: "设备名称",
      required: true,
    },
    {
      prop: "deviceType",
      label: "接口类型",
      required: true,
      as: "select",
      options: {
        loadMethod: () => {
          return [
            {
              label: "平台对接",
              value: "平台对接",
            },
            {
              label: "报文TCP",
              value: "报文TCP",
            },
            {
              label: "报文UDP",
              value: "报文UDP",
            },
          ];
        },
      },
    },

    {
      prop: "transformPort",
      label: "传输端口(10000-60000)",
      required: true,
    },
    {
      prop: "ipWhiteList",
      label: "ip白名单",
      required: true,
    },

    {
      prop: "deviceIdentityResolve",
      label: "设备标识解析器",
      required: true,
    },
    {
      prop: "deviceDefaultIdentityResolve",
      label: "默认设备解析器",
    },
    {
      prop: "versionNumber",
      label: "版本号",
    },
    {
      prop: "deviceCategory",
      label: "设备类别",
      as: "select",
      options: {
        loadMethod: () => $api.dict.item.listAsOptions("device_category"),
      },
    },
  ];

  const editProps: EditFormProps = {
    model: editingObj.value,
    items: formItems,
    columns: 2,
    size: "middle",
    loading: loadingMap.save,
    onClose: () => {
      editingObj.value = null;
    },
    onCancel: () => {
      editingObj.value = null;
    },
    onValidate: (model) => {
      request("save", model);
    },
  };

  return editProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
    case "edit":
      editingObj.value = $api.lis.equipment.$$createEntity(model);
      break;
    case "destroy":
      request("destroy", model ? model.id : "");

      break;
  }
};
</script>

<style lang="less" scoped></style>
